package com.wenmang.networklib.frame;

import com.wenmang.networklib.utils.LogUtils;

import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * desc:
 * 1.对方 IHttpService 的扩展实现
 * author: created by zhoujx on 2018/10/19 15:00
 */
public class JSONHttpService implements IHttpService {
    private static final String TAG = "JSONHttpService";
    private String url;
    private byte[] requestParams;
    private IHttpListener httpListener;

    @Override
    public void setUrl(String url) {
        this.url = url;
    }

    @Override
    public void setParmas(byte[] requestParams) {
        this.requestParams = requestParams;
    }

    @Override
    public void setHttpListener(IHttpListener httpListener) {
        this.httpListener = httpListener;
    }

    @Override
    public void execute() {
        connectionNetwork();
    }

    private void connectionNetwork() {
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(this.url);
            urlConnection = (HttpURLConnection) url.openConnection();
            // 设置这个连接可以写入数据
            urlConnection.setDoInput(true);
            // 设置这个连接可以输出数据
            urlConnection.setDoOutput(true);
            // 不使用缓存
            urlConnection.setUseCaches(false);
            // 连接超时时间
            urlConnection.setConnectTimeout(6000);
            // 响应超时时间
            urlConnection.setReadTimeout(3000);
            // 设置请求的方式
            urlConnection.setRequestMethod("POST");
            // 设置参数类型是 json格式
            urlConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

            // 开始连接
            urlConnection.connect();

            // 获取输出流数据
            OutputStream outputStream = urlConnection.getOutputStream();
            // 缓冲输出流包装字节
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
            if (null != requestParams) {
                // 字节数据写入缓冲区
                bufferedOutputStream.write(requestParams);
            }
            // 刷新缓冲区，发送数据
            bufferedOutputStream.flush();
            outputStream.close();
            bufferedOutputStream.close();

            // 得到服务端返回数据
            if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = urlConnection.getInputStream();
                if (null != httpListener) {
                    httpListener.onSuccess(inputStream);
                }
            } else {
                // TODO: 2018/10/19 失败情况
            }

        } catch (Exception e) {
            LogUtils.e(TAG, e.getMessage());
            if (null != httpListener) {
                httpListener.onFailure(e.getMessage());
            }
        } finally {
            // 关闭TCP链接，释放资源
            if (null != urlConnection)
                urlConnection.disconnect();
        }
    }
}
